<?php

namespace App\Http\Controllers\User;

use Illuminate\Support\Facades\Auth;
use App\Http\Requests\RoleipRequest;
use App\Http\Requests\RoleRequest;
use App\Http\Requests\PermissionupRequest;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;

/**
 * 角色管理类
 * Class RoleController
 * @package App\Http\Controllers\User
 */
class RoleController extends Controller
{
    public function index(){
        $role = Role::where('active','0')->where('partid',Auth::user()->partid)->paginate(10);
        return view('akl.admin.Role_index')->with('role',$role);
    }

    /**
     *
     * @return $this
     */
    public function add(){
        $rel = $this->querypermission();
        return view('akl.admin.Role_add')->with(array('permission'=>$rel));
    }

    public function store( RoleRequest $request ){
        $all = Input::all();
        $all['permission_ids'] = implode( ',', $all['permission_ids']);
        $all['partid'] = Auth::user()->partid;
        $rel = Role::create($all);
        if($rel->wasRecentlyCreated) return back()->with('errors',"添加成功");
        return back()->with('errors',"添加失败，请重试");
    }

    public function destroy($id){
        $rel = Role::where('id',$id)->where('partid',Auth::user()->partid)->update(['active' =>1]);
        if($rel) return back()->with('errors',"删除成功");
        return back()->with('errors',"删除失败，请重试");
    }

    public function edit($id){
        $role = Role::where('partid',Auth::user()->partid)->find($id);
        if(!$role) return back()->with('errors',"无此角色");
        $role->permission_ids = explode(',',$role->permission_ids);
        $permission = $this->querypermission();
        return view('akl.admin.Role_edit',compact('role','permission') );
    }

    public function save( RoleipRequest $request  ){
        $rel = Role::hasrole($request->all()['id']);
        if(!$rel) return back()->with('errors','无此角色');
        $rel = Input::except('_token','send');
        $rel['permission_ids'] = implode(',',$rel['permission_ids']);
        $rel = Role::where('id',$rel['id'])->update($rel);
        if($rel) return back()->with('errors',"更新成功");
        return back()->with('errors',"更新失败，请重试");
    }

    private function querypermission(){
        if(Auth::user()->partid==1){
            $rel = Permission::all();
        }else{
            $rel = Permission::where('permisson','0')->where('active','0')->get();
        }
        for( $i=0;$i<count($rel);$i++ ){
            $rel[$i]->display_name= preg_replace("/Ｌ[　]{0,}/", "", $rel[$i]->display_name);
            $rel[$i]->ids = $i+1;
        }
        return $rel;
    }

}
